package controllers;

import play.*;
import play.Logger;

import play.mvc.*;

import java.util.*;

import models.*;

import play.data.validation.*;

public class ClientOrders extends Controller
{
	private static long pclientId;

	private static ArrayList<Product> sessionProducts;

	public static void index()
	{
		List<Client> clients = Client.findAll();
	
		render(clients);
	}

	public static void show(Long id)
	{
		ClientOrder order = ClientOrder.findById(id);
		
		List<LineItem> itens = LineItem.find("byClientOrder", order).fetch();
					
		render(order, itens);		
    }
	
	public static void create()
	{
		List<Client> clients = Client.findAll();
		
		List<Product> cartList = sessionProducts;
			
		render(clients, cartList);
	}
	
	public static void save(Long clientId, Long productId)
	{
		pclientId = clientId;
		/*if(validation.hasErrors())
		{
			params.flash();
			validation.keep();
			create();
		}*/
		
		if(sessionProducts == null)
		{
			sessionProducts = new ArrayList<Product>();
		}
		
		params.flash();
		
		Product product = Product.findById(productId);
		
		sessionProducts.add(product);
				
		create();
	}
	
	public static void update(Long id)
	{
		Client client = Client.findById(id);
		
		render(client);
	}
	
	public static void doUpdate(@Valid Client client)
	{
		if(validation.hasErrors())
		{
			params.flash();
			validation.keep();
			update(client.id);
		}
	
		client.save();
		
		show(client.id);
	}
	
	public static void delete(Long id)
	{
		Client client = Client.findById(id);
		
		client.delete();
		
		index();
	}
	
	public static void removeLineItem(Integer productIndex)
	{
		sessionProducts.remove(productIndex-1);
				
		params.flash();
	
		create();
	
	}
	
	public static void closeOrder()
	{
		Client client = Client.findById(pclientId);
	
		ClientOrder clientOrder = new ClientOrder(client);
		
		clientOrder.save();
	
		for(int p = 0; p < sessionProducts.size(); p++)
		{
			Product product = sessionProducts.get(p);
			
			LineItem lineItem = new LineItem(product.name, product.description, product.price, clientOrder);
			
			lineItem.save();
		}
				
		create();
	}	
}